export const toPrice = (x: number): string => {
    if (isNaN(x)) {
        return '0.00';
    }

    const f1 = x / 100;
    const roundedF = Math.round(f1 * 100) / 100;
    let s = roundedF.toString();
    let rs = s.indexOf('.');

    if (rs < 0) {
        rs = s.length;
        s += '.';
    }

    while (s.length <= rs + 2) {
        s += '0';
    }

    return s;
};

interface FormatObj {
    y: number;
    m: number;
    d: number;
    h: number;
    i: number;
    s: number;
    a: number;
  }
  
  export function parseTime(time: Date | string | number, cFormat?: string): string | null {
    if (arguments.length === 0 || !time) {
      return null;
    }
  
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
    let date: Date;
  
    if (typeof time === 'object' && time instanceof Date) {
      date = time;
    } else if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        date = new Date(parseInt(time, 10));
      } else {
        // support safari
        date = new Date(time.replace(/-/g, '/'));
      }
    } else if (typeof time === 'number') {
      if (time.toString().length === 10) {
        time *= 1000;
      }
      date = new Date(time);
    } else {
      throw new Error('Invalid time input');
    }
  
    const formatObj: FormatObj = {
      y: date.getFullYear(),
      m: date.getMonth() + 1,
      d: date.getDate(),
      h: date.getHours(),
      i: date.getMinutes(),
      s: date.getSeconds(),
      a: date.getDay(),
    };
  
    const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
      const value = formatObj[key as keyof FormatObj];
      if (key === 'a') {
        return ['日', '一', '二', '三', '四', '五', '六'][value];
      }
      return value.toString().padStart(2, '0');
    });
  
    return time_str;
  }


  export function formatTime(time: string | number, option?: string): string {
    if (!time) {
      return '';
    }
  
    let timestamp: number;
    if (typeof time === 'string' && time.length === 10) {
      timestamp = parseInt(time, 10) * 1000;
    } else {
      timestamp = Number(time);
    }
  
    const d = new Date(timestamp);
    const now = Date.now();
  
    const diff = (now - d.getTime()) / 1000;
  
    if (diff < 30) {
      return '刚刚';
    } else if (diff < 3600) {
      return `${Math.ceil(diff / 60)}分钟前`;
    } else if (diff < 3600 * 24) {
      return `${Math.ceil(diff / 3600)}小时前`;
    } else if (diff < 3600 * 24 * 2) {
      return '1天前';
    }
  
    if (option) {
      return parseTime(d, option) || '';
    } else {
      return `${d.getMonth() + 1}月${d.getDate()}日${d.getHours()}时${d.getMinutes()}分`;
    }
  }